<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="80px"
    >
      <el-form-item label="一级科室" prop="parentId">
        <el-select v-model="queryParams.parentId" placeholder="请选择一级科室" clearable>
          <el-option
            v-for="dept in firstLevelDepartments"
            :key="dept.id"
            :label="dept.name"
            :value="dept.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="二级科室" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入二级科室名称" clearable />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['hospital:department:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['hospital:department:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 科室列表 -->
    <el-table v-loading="loading" :data="departmentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="一级科室" align="center" prop="parentName" />
      <el-table-column label="二级科室" align="center" prop="name" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['hospital:department:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['hospital:department:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改科室信息 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="一级科室" prop="parentId">
          <el-select v-model="form.parentId" placeholder="请选择一级科室">
            <el-option
              v-for="dept in firstLevelDepartments"
              :key="dept.id"
              :label="dept.name"
              :value="dept.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="二级科室名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入二级科室名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDepartment, getDepartment, delDepartment, addDepartment, updateDepartment } from "@/api/hospital/department";

export default {
  name: "Department",
  data() {
    return {
      loading: true,
      departmentList: [],
      total: 0,
      showSearch: true,
      open: false,
      title: "",
      firstLevelDepartments: [], // 存储一级科室数据
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        parentId: null,
        name: null
      },
      form: {},
      rules: {
        parentId: [{ required: true, message: "请选择一级科室", trigger: "change" }],
        name: [{ required: true, message: "二级科室名称不能为空", trigger: "blur" }]
      }
    };
  },
  created() {
    this.getList();
    this.getFirstLevelDepartments();
  },
  methods: {
    async getList() {
      this.loading = true;
      try {
        const response = await listDepartment(this.queryParams);
        this.departmentList = response.rows;
        this.total = response.total;
      } finally {
        this.loading = false;
      }
    },
    async getFirstLevelDepartments() {
      // 获取一级科室
      const response = await listDepartment({ parentId: null });
      this.firstLevelDepartments = response.rows || [];
    },
    resetQuery() {
      this.queryParams = { pageNum: 1, pageSize: 10, parentId: null, name: null };
      this.getList();
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加二级科室";
    },
    handleUpdate(row) {
      this.reset();
      getDepartment(row.id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改二级科室";
      });
    },
    async submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id) {
            updateDepartment(this.form).then(() => {
              this.$message.success("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDepartment(this.form).then(() => {
              this.$message.success("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleDelete(row) {
      this.$confirm("是否确认删除该科室？").then(() => {
        delDepartment(row.id).then(() => {
          this.$message.success("删除成功");
          this.getList();
        });
      });
    },
    reset() {
      this.form = { id: null, parentId: null, name: "" };
      this.resetForm("form");
    }
  }
};
</script>
